//
//  WDProduct.m
//  Zhihuijinfu
//
//  Created by 王笛 on 2016/12/7.
//  Copyright © 2016年 王笛. All rights reserved.
//

#import "WDProduct.h"

@implementation WDProduct

//编码
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    unsigned int outCount = 0;
    
    Ivar *ivars = class_copyIvarList([self class], &outCount);
    
    for (int i = 0; i < outCount; i++) {
        
        Ivar ivar = ivars[i];
        
        //取出第i个实例变量的名字
        const char *name = ivar_getName(ivar);
        
        NSString *nameStr = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
        
        //赋值
        id value = [self valueForKey:nameStr];
        
        //归档
        [aCoder encodeObject:value forKey:nameStr];
    }
    
    //释放变量
    free(ivars);
}

//解码
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super init]) {
        
        unsigned int outCount = 0;
        
        Ivar *ivars = class_copyIvarList([self class], &outCount);
        
        for (int i = 0; i < outCount; i++) {
            
            Ivar ivar = ivars[i];
            
            const char *name = ivar_getName(ivar);
            
            NSString *key = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
            
            id value = [aDecoder decodeObjectForKey:key];
            
            //成员变量赋值
            [self setValue:value forKey:key];
        }
        //释放变量
        free(ivars);
    }
    return self;
}

@end
